<?php
/*
	本插件：$this->model('model')->方法名();
	其他地方调用：model('jy_douyintui/model')->方法名();
*/
namespace jy_douyintui;
defined('BY_JYA') or exit('error');
class model extends \plugin{
	public function checkmerchlogin($merchid){
		if(!$_SESSION['uid']){
			$url=custom_url('jy_douyintui/merchlogin/',true);
			exi('请先登录','error',$url);
		}
		if($merchid){
			$mid = $this->pdo_getcolumn('merch',array('uniacid'=>$_SESSION['uniacid'],'id'=>$merchid),'mid');
			if($mid !=$_SESSION['uid']){
				unset($_SESSION['merchid']);
				$merchid=0;
			}
		}
		if(!$merchid){
			$merchid = $this->pdo_getcolumn('merch',array('uniacid'=>$_SESSION['uniacid'],'mid'=>$_SESSION['uid']),'id');
		}
		return $merchid;
	}
	public function upvideo($video,$isexi=false){
		if(!$video){
			$return['error']=1;
			$return['message']='没有视频源!';
			return $return;
		}
		if($_SESSION['openid']){
			$fans=model('core/fans')->get_fansinfo($_SESSION['openid'],10,$this->setting['client_key']);
		}else{
			$return['error']=1;
			$return['message']='没有获取到OPENID!';
			return $return;
		}
		$access_token=$fans['access_token'];
		if(!$access_token){
			$return['error']=1;
			$return['message']='access_token未获取!';
			if($isexi && $return['error']==1){
				exi($return['message'],'error');
			}
			return $return;
		}
		if(!$this->setting['client_key']){
			$return['error']=1;
			$return['message']='client_key未填写!';
			if($isexi && $return['error']==1){
				exi($return['message'],'error');
			}
			return $return;
		}
		$url = 'https://open.douyin.com/video/upload?access_token='.$access_token.'&open_id='.$_SESSION['openid'];
		$ext=strrchr($video,'.');		
		$ext=strtolower($ext);
		if(ATTACHMENT_TYPE){
			//远程附件
			$video=tomedia($video);
			$temp=ROOT_AT.random(30).$ext;
			copy($video,$temp);
		}else{
			$temp=ROOT_AT.$video;
		}
		$post=array('video'=>'@'.$temp);
		$post=ijson_encode($post);
		$res = $this->curl_upload_file($url,$temp);
		$content = @json_decode($res['content'], true);
		$return = $content['data'];
		if($return['error_code']) {
			$return['error']=1;
			$return['message']='上传视频失败！错误代码-' . $content['error_code'] . '，错误信息-' . $content['description'];
		}
		if($isexi && $return['error']==1){
			exi($return['message'],'error');
		}
		return $return;
	}
	public function createvideo($video_id,$item=array()){
		if(!$video_id){
			$return['error']=1;
			$return['message']='没有视频源video_id!';
			return $return;
		}
		if($_SESSION['openid']){
			$fans=model('core/fans')->get_fansinfo($_SESSION['openid'],10,$this->setting['client_key']);
		}else{
			$return['error']=1;
			$return['message']='没有获取到OPENID，无法创建视频！';
			return $return;
		}
		$access_token=$fans['access_token'];
		if(!$access_token){
			$return['error']=1;
			$return['message']='access_token未获取!';
			if($isexi && $return['error']==1){
				exi($return['message'],'error');
			}
			return $return;
		}
		if(!$this->setting['client_key']){
			$return['error']=1;
			$return['message']='client_key未填写!';
			if($isexi && $return['error']==1){
				exi($return['message'],'error');
			}
			return $return;
		}
		$url = 'https://open.douyin.com/video/create?access_token='.$access_token.'&open_id='.$_SESSION['openid'];
		$post=array('video_id'=>$video_id,'text'=>$item['title']);
		$post=ijson_encode($post);
		$res = cfc('http')->ihttp_json($url,$post);
		$content = @json_decode($res['content'], true);
		$return = $content['data'];
		if($content['error_code']) {
			$return['error']=1;
			$return['message']='创建视频失败！错误代码-' . $content['error_code'] . '，错误信息-' . $content['description'];
		}
		if($isexi && $return['error']==1){
			exi($return['message'],'error');
		}
		return $return;
	}
	public function getAccessToken($code,$isexi=false){//获取access_token
		if($_SESSION['openid']){
			$fans=model('core/fans')->get_fansinfo($_SESSION['openid'],10,$this->setting['client_key']);
			return $fans;
		}
		$return['error']=0;
		if(!$_SESSION['openid']){
			$url = "https://open.douyin.com/oauth/access_token?client_key=".$this->setting['client_key']."&client_secret=".$this->setting['client_secret']."&grant_type=authorization_code&code=".$code;
			$post=array('from'=>'jinyun');
			$post=ijson_encode($post);
			$content = cfc('http')->ihttp_request($url,$post);
			if(is_error($content)){
				$return['error']=1;
				$return['message']='抖音号授权失败, 请稍后重试！错误详情: ' . $content['message'];
				if($isexi){
					exi($return['message'],'error');
				}else{
					return $return;
				}
			}
			$token = @json_decode($content['content'], true);
			$token = $token['data'];
			if($token['error_code']) {
				$return['error']=1;
				$return['message']='抖音号授权失败, 请稍后重试！ 错误代码-' . $token['error_code'] . '，错误信息-' . $token['description'];
				if($isexi){
					exi($return['message'],'error');
				}else{
					return $return;
				}
			}
			if(!$token['open_id']){
				$return['error']=1;
				$return['message']='获取open_id失败！';
			}
			if(!$token['open_id'] || $return['error']==1){
				if($isexi){
					exi($return['message'],'error');
				}else{
					return $return;
				}
			}
			$_SESSION['openid']=$token['open_id'];
			$fans=model('core/fans')->get_fansinfo($token['open_id'],10,$this->setting['client_key']);
			$update=array(
				'access_token' => $token['access_token'],
				'refresh_token' => $token['refresh_token'],
				'client_id' => $this->setting['client_key'],
				'refresh_time' => TIMESTAMP + $token['expires_in']
			);
			if($fans['id']){
				$uid=$fans['mid'];
				pdo_update('core_fans',$update,array('id'=>$fans['id']));
			}else{
				$update['uniacid'] = $_SESSION['uniacid'];
				$update['type'] = 10;
				$update['openid'] = $_SESSION['openid'];
				$update['plugin']='jy_douyintui';
				$update['createtime']=TIMESTAMP;
				pdo_insert('core_fans',$update);
				$fansid=pdo_insertid();
				do{
					$username='douyin_'.random(10);
				}while(pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'username'=>$username),'id'));
				$new_member=array(
					'uniacid'=>$_SESSION['uniacid'],
					'from_os'=>10,
					'createtime'=>TIMESTAMP,
					'username'=>$username,
				);
				$uid=model('core/member')->register($new_member);
				pdo_update('core_fans',array('mid'=>$uid),array('id'=>$fansid));
			}
			model('core/member')->login($uid);
		}
		$return['access_token']=$update['access_token'];
		return $return;
	}
	public function getuserinfo($open_id='',$access_token=''){
		$open_id=$open_id?:$_SESSION['openid'];
		if(!$open_id){
			return false;
		}
		$url = "https://open.douyin.com/oauth/userinfo?open_id=".$open_id."&access_token=".$access_token;
		$post=array('from'=>'jinyun');
		$post=ijson_encode($post);
		$content = cfc('http')->ihttp_request($url,$post);
		if(is_error($content)){
				$return['error']=1;
				$return['message']='抖音号获取粉丝失败, 请稍后重试！错误详情: ' . $content['message'];
				return $return;
		}
		$info = @json_decode($content['content'], true);
		$info = $info['data'];
		if($info['error_code']) {
				$return['error']=1;
				$return['message']='抖音号获取粉丝失败, 请稍后重试 错误代码-' . $info['error_code'] . '，错误信息-' . $info['description'];
				return $return;
		}
		$fans=model('core/fans')->get_fansinfo($open_id,10,$this->setting['client_key']);
		$update=array(
				'nickname'=>$info['nickname'],
				'avatar'=>$info['avatar']?:$info['avatar'],
				'pcd'=>$info['country'].$info['province'].$info['city'],
				'sex'=>$info['gender'],
		);
		pdo_update('core_fans',$update,array('id'=>$fans['id']));
		$member_update=array();
		if(!$member['nickname']){
				$member_update['nickname']=$update['nickname'];
		}
		if(!$member['avatar']){
				$member_update['avatar']=$update['avatar'];
		}
		if(!$member['sex']){
				$member_update['sex']=$update['sex'];
		}
		if($member_update){
				model('core/member')->member_update($fans['mid'],$member_update);
		}
	}
	public function upvideodata($video=array(),$open_id=''){
		if(!$open_id){
			$fans=model('core/fans')->get_fansinfo($video['mid'],10,$this->setting['client_key']);
			$open_id=$fans['open_id'];
		}else{
			$fans=model('core/fans')->get_fansinfo($open_id,10,$this->setting['client_key']);
		}
		$url = "https://open.douyin.com/data/external/item/base?open_id=".$open_id."&access_token=".$fans['access_token'].'&item_id='.$video['item_id'];
		$post=array('from'=>'jinyun');
		$post=ijson_encode($post);
		$content = cfc('http')->ihttp_request($url,$post);
		if(is_error($content)){
				$return['error']=1;
				$return['message']='抖音号获取视频数据, 请稍后重试！错误详情: ' . $content['message'];
				return $return;
		}
		$info = @json_decode($content['content'], true);
		$info = $info['data'];
		if($info['error_code']) {
				$return['error']=1;
				$return['message']='抖音号获取视频数据, 请稍后重试 错误代码-' . $info['error_code'] . '，错误信息-' . $info['description'];
				return $return;
		}
		if($info['result']){
			$update=array(
				'data'=>ijson_encode($info['result']),
				'avg_play_duration'=>$info['result']['avg_play_duration'],
				'total_comment'=>$info['result']['total_comment'],
				'total_like'=>$info['result']['total_like'],
				'total_play'=>$info['result']['total_play'],
				'total_share'=>$info['result']['total_share'],
				'updatatime'=>TIMESTAMP,
			);
			$this->pdo_update('video_log',$update,array('id'=>$video['id']));
		}
		return true;
	}
	public function add_member($mid,$post=array()){
		$member=$this->pdo_get('member',array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
		$update=array();
		if($post['mobile']){
			$update['mobile'] = $post['mobile'];
		}
		if($member['id']){
			if($update){
				$this->pdo_update('member',$update,array('mid'=>$mid,'uniacid'=>$_SESSION['uniacid']));
			}
		}else{
			$update['uniacid'] = $_SESSION['uniacid'];
			$update['agent_id'] = $post['agent_id'];
			$update['mid']=$mid;
			$update['createtime']=TIMESTAMP;
			$this->pdo_insert('member',$update);
		}
		return true;
	}
	public function get_poster($url,$poster=array()){
		$qr=cfc('tools')->createqrcode($url,150,true);
		$poster['id']='jy_douyintui'.$poster['id'];
		$img=model('jy_poster/model')->createPoster($poster,$qr,'','');
		return tomedia($img);
	}
	public function add_saolog($item){
		$update=array(
			'uniacid' => $_SESSION['uniacid'],
			'game_id' => $item['id'],
			'mid'=>$_SESSION['uid'],
			'createtime'=>TIMESTAMP
		);
		$this->pdo_insert('sao_log',$update);
		return true;
	}
	public function add_video_log($item,$item_id=''){
		$update=array(
			'uniacid' => $_SESSION['uniacid'],
			'game_id' => $item['id'],
			'mid'=>$_SESSION['uid'],
			'video' => $item['video_datas'][0]['url'],
			'item_id' => $item_id,
			'createtime'=>TIMESTAMP
		);
		$this->pdo_insert('video_log',$update);
		$this->add_dian_log($item);
		return true;
	}
	public function check_diannum($item){
		if($item['merchid']){
			$merch=$this->pdo_get('merch',array('id'=>$item['merchid']));
			if($merch['diannum']<=0){
				return false;
			}
		}
		return true;
	}
	public function check_upvideo($item,$mid=0){
		$mid=$mid?:$_SESSION['uid'];
		$update=array(
			'uniacid' => $_SESSION['uniacid'],
			'game_id' => $item['id'],
			'mid'=>$mid,
		);
		$is=$this->pdo_get('video_log',$update,'id');
		return $is;
	}
	public function add_hexiaolog($item){
		$update=array(
			'uniacid' => $_SESSION['uniacid'],
			'game_id' => $item['id'],
			'user_id'=>$_SESSION['uid'],
			'mid'=>$item['mid'],
			'createtime'=>TIMESTAMP
		);
		$this->pdo_insert('hexiao_log',$update);
		return true;
	}
	public function add_dian_log($item=array(),$isadd=0,$num=1){
		$update=array(
			'uniacid' => $_SESSION['uniacid'],
			'game_id' => $item['id'],
			'isadd'=>$isadd,
			'mid'=>$_SESSION['uid'],
			'num'=>$num,
			'merchid'=>$item['merchid'],
			'createtime'=>TIMESTAMP
		);
		$this->pdo_insert('dian_log',$update);
		if($item['merchid']){
			if($isadd){
				$this->pdo_update('merch',array('diannum +='=>$num),array('id'=>$item['merchid']));
			}else{
				$this->pdo_update('merch',array('diannum -='=>$num),array('id'=>$item['merchid']));
			}
		}
		return true;
	}
	public function add_coupon_log($item){
		if(!$_SESSION['uid']){
			exi('领取失败！请先授权登录！','error');
		}
		$isget=$this->pdo_get('coupon_log',array('mid'=>$_SESSION['uid'],'coupon_id'=>$item['coupon_id'],'game_id'=>$item['game_id']));
		if($isget['id']){
			exi('您已经领券了本活动的优惠券！','error');
		}
		model('jy_weishop/coupon')->getcoupon($item['coupon_id'],'',true);
		$update=array(
			'uniacid' => $_SESSION['uniacid'],
			'game_id' => $item['game_id'],
			'coupon_id'=>$item['coupon_id'],
			'mid'=>$_SESSION['uid'],
			'createtime'=>TIMESTAMP
		);
		$this->pdo_insert('coupon_log',$update);
		return true;
	}
		/**
      * @param $file 文件路径 
      * @param $url  请求url 带上传凭证
    */    
    function curl_upload_file($url,$file) {
        $payload = '';
        $params  = "--ABC1234\r\n"
            . "Content-Type: application/x-www-form-urlencoded\r\n"
            . "\r\n"
            . $payload . "\r\n"
            . "--ABC1234\r\n"
            . "Content-Type: video/mp4\r\n"
            . "Content-Disposition: form-data; name=\"video\"; filename=\"1.mp4\"\r\n"
            . "\r\n"
            . file_get_contents($file) . "\r\n"
            . "--ABC1234--";
 
        $first_newline      = strpos($params, "\r\n");
        $multipart_boundary = substr($params, 2, $first_newline - 2);
        $request_headers    = array();
        $request_headers[]  = 'Content-Length: ' . strlen($params);
        $request_headers[]  = 'Content-Type: multipart/form-data; boundary=' . $multipart_boundary;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $reply = curl_exec($ch);
		$res['content']=$reply;
        return $res;
	}
    public function decrypt($encrypted_mobile,$client_secret=''){
		$client_secret=$client_secret?:$this->setting['client_secret'];
        $iv = substr($client_secret, 0, 16);
        return openssl_decrypt($encrypted_mobile, 'aes-256-cbc', $client_secret, 0, $iv);
    }
}
?>